<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>41.2. Zend_Test_PHPUnit</title>
<link rel="stylesheet" href="dbstyle.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.72.0">
<link rel="start" href="index.html" title="Programmer's Reference Guide">
<link rel="up" href="zend.test.html" title="Chapter 41. Zend_Test">
<link rel="prev" href="zend.test.html" title="Chapter 41. Zend_Test">
<link rel="next" href="zend.text.html" title="Chapter 42. Zend_Text">
<link rel="chapter" href="introduction.html" title="Chapter 1. Introduction to Zend Framework">
<link rel="chapter" href="zend.acl.html" title="Chapter 2. Zend_Acl">
<link rel="chapter" href="zend.auth.html" title="Chapter 3. Zend_Auth">
<link rel="chapter" href="zend.cache.html" title="Chapter 4. Zend_Cache">
<link rel="chapter" href="zend.config.html" title="Chapter 5. Zend_Config">
<link rel="chapter" href="zend.console.getopt.html" title="Chapter 6. Zend_Console_Getopt">
<link rel="chapter" href="zend.controller.html" title="Chapter 7. Zend_Controller">
<link rel="chapter" href="zend.currency.html" title="Chapter 8. Zend_Currency">
<link rel="chapter" href="zend.date.html" title="Chapter 9. Zend_Date">
<link rel="chapter" href="zend.db.html" title="Chapter 10. Zend_Db">
<link rel="chapter" href="zend.debug.html" title="Chapter 11. Zend_Debug">
<link rel="chapter" href="zend.dojo.html" title="Chapter 12. Zend_Dojo">
<link rel="chapter" href="zend.dom.html" title="Chapter 13. Zend_Dom">
<link rel="chapter" href="zend.exception.html" title="Chapter 14. Zend_Exception">
<link rel="chapter" href="zend.feed.html" title="Chapter 15. Zend_Feed">
<link rel="chapter" href="zend.filter.html" title="Chapter 16. Zend_Filter">
<link rel="chapter" href="zend.form.html" title="Chapter 17. Zend_Form">
<link rel="chapter" href="zend.gdata.html" title="Chapter 18. Zend_Gdata">
<link rel="chapter" href="zend.http.html" title="Chapter 19. Zend_Http">
<link rel="chapter" href="zend.infocard.html" title="Chapter 20. Zend_InfoCard">
<link rel="chapter" href="zend.json.html" title="Chapter 21. Zend_Json">
<link rel="chapter" href="zend.layout.html" title="Chapter 22. Zend_Layout">
<link rel="chapter" href="zend.ldap.html" title="Chapter 23. Zend_Ldap">
<link rel="chapter" href="zend.loader.html" title="Chapter 24. Zend_Loader">
<link rel="chapter" href="zend.locale.html" title="Chapter 25. Zend_Locale">
<link rel="chapter" href="zend.log.html" title="Chapter 26. Zend_Log">
<link rel="chapter" href="zend.mail.html" title="Chapter 27. Zend_Mail">
<link rel="chapter" href="zend.measure.html" title="Chapter 28. Zend_Measure">
<link rel="chapter" href="zend.memory.html" title="Chapter 29. Zend_Memory">
<link rel="chapter" href="zend.mime.html" title="Chapter 30. Zend_Mime">
<link rel="chapter" href="zend.openid.html" title="Chapter 31. Zend_OpenId">
<link rel="chapter" href="zend.paginator.html" title="Chapter 32. Zend_Paginator">
<link rel="chapter" href="zend.pdf.html" title="Chapter 33. Zend_Pdf">
<link rel="chapter" href="zend.registry.html" title="Chapter 34. Zend_Registry">
<link rel="chapter" href="zend.rest.html" title="Chapter 35. Zend_Rest">
<link rel="chapter" href="zend.search.lucene.html" title="Chapter 36. Zend_Search_Lucene">
<link rel="chapter" href="zend.server.html" title="Chapter 37. Zend_Server">
<link rel="chapter" href="zend.service.html" title="Chapter 38. Zend_Service">
<link rel="chapter" href="zend.session.html" title="Chapter 39. Zend_Session">
<link rel="chapter" href="zend.soap.html" title="Chapter 40. Zend_Soap">
<link rel="chapter" href="zend.test.html" title="Chapter 41. Zend_Test">
<link rel="chapter" href="zend.text.html" title="Chapter 42. Zend_Text">
<link rel="chapter" href="zend.timesync.html" title="Chapter 43. Zend_TimeSync">
<link rel="chapter" href="zend.translate.html" title="Chapter 44. Zend_Translate">
<link rel="chapter" href="zend.uri.html" title="Chapter 45. Zend_Uri">
<link rel="chapter" href="zend.validate.html" title="Chapter 46. Zend_Validate">
<link rel="chapter" href="zend.version.html" title="Chapter 47. Zend_Version">
<link rel="chapter" href="zend.view.html" title="Chapter 48. Zend_View">
<link rel="chapter" href="zend.xmlrpc.html" title="Chapter 49. Zend_XmlRpc">
<link rel="appendix" href="requirements.html" title="Appendix A. Zend Framework Requirements">
<link rel="appendix" href="coding-standard.html" title="Appendix B. Zend Framework Coding Standard for PHP">
<link rel="appendix" href="copyrights.html" title="Appendix C. Copyright Information">
<link rel="index" href="the.index.html" title="Index">
<link rel="subsection" href="zend.test.phpunit.html#zend.test.phpunit.bootstrapping" title="41.2.1. Bootstrapping your TestCase">
<link rel="subsection" href="zend.test.phpunit.html#zend.test.phpunit.testing" title="41.2.2. Testing your Controllers and MVC Applications">
<link rel="subsection" href="zend.test.phpunit.html#zend.test.phpunit.assertions" title="41.2.3. Assertions">
<link rel="subsection" href="zend.test.phpunit.html#zend.test.phpunit.examples" title="41.2.4. Examples">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader"><table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">41.2. Zend_Test_PHPUnit</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="zend.test.html">Prev</a> </td>
<th width="60%" align="center">Chapter 41. Zend_Test</th>
<td width="20%" align="right"> <a accesskey="n" href="zend.text.html">Next</a>
</td>
</tr>
</table></div>
<div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="zend.test.phpunit"></a>41.2. Zend_Test_PHPUnit</h2></div></div></div>
<p>
        <code class="code">Zend_Test_PHPUnit</code> provides a TestCase for MVC applications
        that contains assertions for testing against a variety of
        responsibilities. Probably the easiest way to understand what it can do
        is to see an example.
    </p>
<div class="example">
<a name="zend.test.phpunit.loginexample"></a><p class="title"><b>Example 41.1. Application Login TestCase example</b></p>
<div class="example-contents">
<p>
            The following is a simple test case for a
            <code class="code">UserController</code> to verify several things:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                The login form should be displayed to non-authenticated users.
            </p></li>
<li><p>
                When a user logs in, they should be redirected to their profile
                page, and that profile page should show relevant information.
            </p></li>
</ul></div>
<p>
            This particular example assumes a few things. First, we're moving
            most of our bootstrapping to a plugin. This simplifies setup of the
            test case as it allows us to specify our environment succinctly,
            and also allows us to bootstrap the application in a single line.
            Also, our particular example is assuming that autoloading is setup
            so we do not need to worry about requiring the appropriate classes
            (such as the correct controller, plugin, etc).
        </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        $this-&gt;bootstrap = array($this, 'appBootstrap');
        parent::setUp();
    }

    public function appBootstrap()
    {
        $this-&gt;frontController-&gt;registerPlugin(new Bugapp_Plugin_Initialize('development'));
    }

    public function testCallWithoutActionShouldPullFromIndexAction()
    {
        $this-&gt;dispatch('/user');
        $this-&gt;assertController('user');
        $this-&gt;assertAction('index');
    }

    public function testIndexActionShouldContainLoginForm()
    {
        $this-&gt;dispatch('/user');
        $this-&gt;assertAction('index');
        $this-&gt;assertQueryCount('form#loginForm', 1);
    }

    public function testValidLoginShouldGoToProfilePage()
    {
        $this-&gt;request-&gt;setMethod('POST')
              -&gt;setPost(array(
                  'username' =&gt; 'foobar',
                  'password' =&gt; 'foobar'
              ));
        $this-&gt;dispatch('/user/login');
        $this-&gt;assertRedirectTo('/user/view');

        $this-&gt;resetResponse();
        $this-&gt;request-&gt;setMethod('GET')
             -&gt;setPost(array());
        $this-&gt;dispatch('/user/view');
        $this-&gt;assertRoute('default');
        $this-&gt;assertModule('default');
        $this-&gt;assertController('user');
        $this-&gt;assertAction('view');
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery('dl');
        $this-&gt;assertQueryContentContains('h2', 'User: foobar');
    }
}
</pre>
<p>
            This example could be written somewhat simpler -- not all the
            assertions shown are necessary, and are provided for illustration
            purposes only. Hopefully, it shows how simple it can be to test
            your applications.
        </p>
</div>
</div>
<br class="example-break"><div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.test.phpunit.bootstrapping"></a>41.2.1. Bootstrapping your TestCase</h3></div></div></div>
<p>
        As noted in the <a href="zend.test.phpunit.html#zend.test.phpunit.loginexample" title="Example 41.1. Application Login TestCase example">Login
            example</a>, all MVC test cases should extend
        <code class="code">Zend_Test_PHPUnit_ControllerTestCase</code>. This class in turn
        extends <code class="code">PHPUnit_Framework_TestCase</code>, and gives you all the
        structure and assertions you'd expect from PHPUnit -- as well as some
        scaffolding and assertions specific to Zend Framework's MVC
        implementation.
    </p>
<p>
        In order to test your MVC application, you will need to bootstrap it.
        There are several ways to do this, all of which hinge on the public
        <code class="code">$bootstrap</code> property.
    </p>
<p>
        First, you can set this property to point to a file. If you do
        this, the file should <span class="emphasis"><em>not</em></span> dispatch the front
        controller, but merely setup the front controller and any application
        specific needs.
    </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $bootstrap = '/path/to/bootstrap/file.php'

    // ...
}
</pre>
<p>
        Second, you can provide a PHP callback to execute in order to bootstrap
        your application. This method is seen in the <a href="zend.test.phpunit.html#zend.test.phpunit.loginexample" title="Example 41.1. Application Login TestCase example">Login example</a>. If
        the callback is a function or static method, this could be set at the
        class level:
    </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $bootstrap = array('App', 'bootstrap');

    // ...
}
</pre>
<p>
        In cases where an object instance is necessary, we recommend performing
        this in your <code class="code">setUp()</code> method:
    </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        // Use the 'start' method of a Bootstrap object instance:
        $bootstrap = new Bootstrap('test');
        $this-&gt;bootstrap = array($bootstrap, 'start');
        parent::setUp();
    }
}
</pre>
<p>
        Note the call to <code class="code">parent::setUp()</code>; this is necessary, as
        the <code class="code">setUp()</code> method of
        <code class="code">Zend_Test_PHPUnit_Controller_TestCase</code> will perform the
        remainder of the bootstrapping process (which includes calling the
        callback).
    </p>
<p>
        During normal operation, the <code class="code">setUp()</code> method will bootstrap
        the application. This process first  will include cleaning up the
        environment to a clean request state, resetting any plugins and
        helpers, resetting the front controller instance, and creating new
        request and response objects. Once this is done, it will then either
        <code class="code">include</code> the file specified in <code class="code">$bootstrap</code>, or
        call the callback specified.
    </p>
<p>
        Bootstrapping should be as close as possible to how the application
        will be bootstrapped. However, there are several caveats:
    </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
            Do not provide alternate implementations of the Request and
            Response objects; they will not be used.
            <code class="code">Zend_Test_PHPUnit_Controller_TestCase</code> uses custom
            request and response objects,
            <code class="code">Zend_Controller_Request_HttpTestCase</code> and
            <code class="code">Zend_Controller_Response_HttpTestCase</code>, respectively.
            These objects provide methods for setting up the request
            environment in targetted ways, and pulling response artifacts in
            specific ways.
        </p></li>
<li><p>
            Do not expect to test server specifics. In other words, the tests
            are not a guarantee that the code will run on a specific server
            configuration, but merely that the application should run as
            expected should the router be able to route the given request. To
            this end, do not set server-specific headers in the request object.
        </p></li>
</ul></div>
<p>
        Once the application is bootstrapped, you can then start creating
        your tests.
    </p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.test.phpunit.testing"></a>41.2.2. Testing your Controllers and MVC Applications</h3></div></div></div>
<p>
        Once you have your bootstrap in place, you can begin testing. Testing
        is basically as you would expect in an PHPUnit test suite, with a few
        minor differences.
    </p>
<p>
        First, you will need to dispatch a URL to test, using the
        <code class="code">dispatch()</code> method of the TestCase:
    </p>
<pre class="programlisting">
class IndexControllerTest extends Zend_Test_PHPUnit_Controller_TestCase
{
    // ...

    public function testHomePage()
    {
        $this-&gt;dispatch('/');
        // ...
    }
}
</pre>
<p>
        There will be times, however, that you need to provide extra
        information -- GET and POST variables, COOKIE information, etc. You can
        populate the request with that information:
    </p>
<pre class="programlisting">
class FooControllerTest extends Zend_Test_PHPUnit_Controller_TestCase
{
    // ...

    public function testBarActionShouldReceiveAllParameters()
    {
        // Set GET variables:
        $this-&gt;request-&gt;setQuery(array(
            'foo' =&gt; 'bar',
            'bar' =&gt; 'baz',
        ));

        // Set POST variables:
        $this-&gt;request-&gt;setPost(array(
            'baz'  =&gt; 'bat',
            'lame' =&gt; 'bogus',
        ));

        // Set a cookie value:
        $this-&gt;request-&gt;setCookie('user', 'matthew');
        // or many:
        $this-&gt;request-&gt;setCookies(array(
            'timestamp' =&gt; time(),
            'host'      =&gt; 'foobar',
        ));

        // Set headers, even:
        $this-&gt;request-&gt;setHeader('X-Requested-With', 'XmlHttpRequest');

        // Set the request method:
        $this-&gt;request-&gt;setMethod('POST');

        // Dispatch:
        $this-&gt;dispatch('/foo/bar');

        // ...
    }
}
</pre>
<p>
        Now that the request is made, it's time to start making assertions
        against it.
    </p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.test.phpunit.assertions"></a>41.2.3. Assertions</h3></div></div></div>
<p>
        Assertions are at the heart of Unit Testing; you use them to verify
        that the results are what you expect. To this end,
        <code class="code">Zend_Test_PHPUnit_ControllerTestCase</code> provides a number of
        assertions to make testing your MVC apps and controllers simpler.
    </p>
<div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.test.phpunit.assertions.query"></a>41.2.3.1. CSS Selector Assertions</h4></div></div></div>
<p>
            CSS selectors are an easy way to verify that certain artifacts are
            present in the response content. They also make it trivial to
            ensure that items necessary for Javascript UIs and/or AJAX
            integration will be present; most JS toolkits provide some
            mechanism for pulling DOM elements based on CSS selectors, so the
            syntax would be the same.
        </p>
<p>
            This functionality is provided via <a href="zend.dom.query.html" title="13.2. Zend_Dom_Query">Zend_Dom_Query</a>, and integrated
            into a set of 'Query' assertions. Each of these assertions takes
            as their first argument a CSS selector, with optionally additional
            arguments and/or an error message, based on the assertion type. You
            can find the rules for writing the CSS selectors in the <a href="zend.dom.query.html#zend.dom.query.operation" title="13.2.1. Theory of Operation">Zend_Dom_Query theory of
                operation chapter</a>.  Query assertions include:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                <code class="code">assertQuery($path, $message = '')</code>: assert that
                one or more DOM elements matching the given CSS selector are
                present. If a <code class="code">$message</code> is present, it will be
                prepended to any failed assertion message.
            </p></li>
<li><p>
                <code class="code">assertQueryContentContains($path, $match, $message =
                    '')</code>: assert that one or more DOM elements matching
                the given CSS selector are present, and that at least one
                contains the content provided in <code class="code">$match</code>. If a
                <code class="code">$message</code> is present, it will be prepended to any
                failed assertion message.
            </p></li>
<li><p>
                <code class="code">assertQueryContentRegex($path, $pattern, $message =
                    '')</code>: assert that one or more DOM elements matching
                the given CSS selector are present, and that at least one
                matches the regular expression provided in
                <code class="code">$pattern</code>. If a <code class="code">$message</code> is present,
                it will be prepended to any failed assertion message.
            </p></li>
<li><p>
                <code class="code">assertQueryContentCount($path, $count, $message =
                    '')</code>: assert that there are exactly
                <code class="code">$count</code> DOM elements matching the given CSS
                selector present. If a <code class="code">$message</code> is present, it
                will be prepended to any failed assertion message.
            </p></li>
<li><p>
                <code class="code">assertQueryContentCountMin($path, $count, $message =
                    '')</code>: assert that there are at least
                <code class="code">$count</code> DOM elements matching the given CSS
                selector present. If a <code class="code">$message</code> is present, it
                will be prepended to any failed assertion message.
                <span class="emphasis"><em>Note:</em></span> specifying a value of 1 for
                <code class="code">$count</code> is the same as simply using
                <code class="code">assertQuery()</code>.
            </p></li>
<li><p>
                <code class="code">assertQueryContentCountMax($path, $count, $message =
                    '')</code>: assert that there are no more than
                <code class="code">$count</code> DOM elements matching the given CSS
                selector present. If a <code class="code">$message</code> is present, it
                will be prepended to any failed assertion message.
                <span class="emphasis"><em>Note:</em></span> specifying a value of 1 for
                <code class="code">$count</code> is the same as simply using
                <code class="code">assertQuery()</code>.
            </p></li>
</ul></div>
<p>
            Additionally, each of the above has a 'Not' variant that provides a
            negative assertion: <code class="code">assertNotQuery()</code>,
            <code class="code">assertNotQueryContentContains()</code>,
            <code class="code">assertNotQueryContentRegex()</code>, and
            <code class="code">assertNotQueryContentCount()</code>. (Note that the min and
            max counts do not have these variants, for what should be obvious
            reasons.)
        </p>
</div>
<div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.test.phpunit.assertions.xpath"></a>41.2.3.2. XPath Assertions</h4></div></div></div>
<p>
            Some developers are more familiar with XPath than with CSS
            selectors, and thus XPath variants of all the <a href="zend.test.phpunit.html#zend.test.phpunit.assertions.query" title="41.2.3.1. CSS Selector Assertions">Query
                assertions</a> are also provided. These are:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                <code class="code">assertXpath($path, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertNotXpath($path, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertXpathContentContains($path, $match, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertNotXpathContentContains($path, $match, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertXpathContentRegex($path, $pattern, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertNotXpathContentRegex($path, $pattern, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertXpathCount($path, $count, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertNotXpathCount($path, $count, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertXpathCountMin($path, $count, $message = '')</code>
            </p></li>
<li><p>
                <code class="code">assertNotXpathCountMax($path, $count, $message = '')</code>
            </p></li>
</ul></div>
</div>
<div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.test.phpunit.assertions.redirect"></a>41.2.3.3. Redirect Assertions</h4></div></div></div>
<p>
            Often an action will redirect. Instead of following the redirect,
            <code class="code">Zend_Test_PHPUnit_ControllerTestCase</code> allows you to
            test for redirects with a handful of assertions.
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                <code class="code">assertRedirect($message = '')</code>: assert simply that
                a redirect has occurred.
            </p></li>
<li><p>
                <code class="code">assertNotRedirect($message = '')</code>: assert that no
                redirect has occurred.
            </p></li>
<li><p>
                <code class="code">assertRedirectTo($url, $message = '')</code>: assert that
                a redirect has occurred, and that the value of the Location
                header is the <code class="code">$url</code> provided.
            </p></li>
<li><p>
                <code class="code">assertNotRedirectTo($url, $message = '')</code>: assert that
                a redirect has either NOT occurred, or that the value of the Location
                header is NOT the <code class="code">$url</code> provided.
            </p></li>
<li><p>
                <code class="code">assertRedirectRegex($pattern, $message = '')</code>:
                assert that a redirect has occurred, and that the value of the
                Location header matches the regular expression provided by
                <code class="code">$pattern</code>.
            </p></li>
<li><p>
                <code class="code">assertNotRedirectRegex($pattern, $message = '')</code>:
                assert that a redirect has either NOT occurred, or that the value of the
                Location header does NOT match the regular expression provided by
                <code class="code">$pattern</code>.
            </p></li>
</ul></div>
</div>
<div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.test.phpunit.assertions.header"></a>41.2.3.4. Response Header Assertions</h4></div></div></div>
<p>
            In addition to checking for redirect headers, you will often need
            to check for specific HTTP response codes and headers -- for
            instance, to determine whether an action results in a 404 or 500
            response, or to ensure that JSON responses contain the appropriate
            Content-Type header. The following assertions are available.
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                <code class="code">assertResponseCode($code, $message = '')</code>: assert
                that the response resulted in the given HTTP response code.
            </p></li>
<li><p>
                <code class="code">assertHeader($header, $message = '')</code>: assert
                that the response contains the given header.
            </p></li>
<li><p>
                <code class="code">assertHeaderContains($header, $match, $message =
                '')</code>: assert that the response contains the given header
                and that its content contains the given string.
            </p></li>
<li><p>
                <code class="code">assertHeaderRegex($header, $pattern, $message =
                '')</code>: assert that the response contains the given header
            and that its content matches the given regex.
            </p></li>
</ul></div>
<p>
            Additionally, each of the above assertions have a 'Not' variant for
            negative assertions.
        </p>
</div>
<div class="sect3" lang="en">
<div class="titlepage"><div><div><h4 class="title">
<a name="zend.test.phpunit.assertions.request"></a>41.2.3.5. Request Assertions</h4></div></div></div>
<p>
            It's often useful to assert against the last run action,
            controller, and module; additionally, you may want to assert
            against the route that was matched. The following assertions can
            help you in this regard:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                <code class="code">assertModule($module, $message = '')</code>: Assert that
                the given module was used in the last dispatched action.
            </p></li>
<li><p>
                <code class="code">assertController($controller, $message = '')</code>:
                Assert that the given controller was selected in the last
                dispatched action.
            </p></li>
<li><p>
                <code class="code">assertAction($action, $message = '')</code>: Assert that
                the given action was last dispatched.
            </p></li>
<li><p>
                <code class="code">assertRoute($route, $message = '')</code>: Assert that
                the given named route was matched by the router.
            </p></li>
</ul></div>
<p>
            Each also has a 'Not' variant for negative assertions.
        </p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.test.phpunit.examples"></a>41.2.4. Examples</h3></div></div></div>
<p>
        Knowing how to setup your testing infrastructure and how to make
        assertions is only half the battle; now it's time to start looking at
        some actual testing scenarios to see how you can leverage them.
    </p>
<div class="example">
<a name="zend.test.phpunit.examples.userController"></a><p class="title"><b>Example 41.2. Testing a UserController</b></p>
<div class="example-contents">
<p>
            Let's consider a standard task for a website: authenticating and registering users. In our example, we'll define a UserController for handling this, and have the following requirements:
        </p>
<div class="itemizedlist"><ul type="disc">
<li><p>
                If a user is not authenticated, they will always be redirected
                to the login page of the controller, regardless of the action
                specified.
            </p></li>
<li><p>
                The login form page will show both the login form and the
                registration form.
            </p></li>
<li><p>
                Providing invalid credentials should result in returning to the
                login form.
            </p></li>
<li><p>
                Valid credentials should result in redirecting to the user
                profile page.
            </p></li>
<li><p>
                The profile page should be customized to contain the user's
                username.
            </p></li>
<li><p>
                Authenticated users who visit the login page should be
                redirected to their profile page.
            </p></li>
<li><p>
                On logout, a user should be redirected to the login page.
            </p></li>
<li><p>
                With invalid data, registration should fail.
            </p></li>
</ul></div>
<p>
            We could, and should define further tests, but these will do for
            now. 
        </p>
<p>
            For our application, we will define a plugin, 'Initialize', that
            runs at <code class="code">routeStartup()</code>. This allows us to encapsulate
            our bootstrap in an OOP interface, which also provides an easy way
            to provide a callback. Let's look at the basics of this class
            first:
        </p>
<pre class="programlisting">
class Bugapp_Plugin_Initialize extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var string Path to application root
     */
    protected $_root;

    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this-&gt;_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../../../');
        }
        $this-&gt;_root = $root;

        $this-&gt;initPhpConfig();

        $this-&gt;_front = Zend_Controller_Front::getInstance();
    }

    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $this-&gt;initDb();
        $this-&gt;initHelpers();
        $this-&gt;initView();
        $this-&gt;initPlugins();
        $this-&gt;initRoutes();
        $this-&gt;initControllers();
    }

    // definition of methods would follow...
}
</pre>
<p>
            This allows us to create a bootstrap callback like the following:
        </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function appBootstrap()
    {
        $controller = $this-&gt;getFrontController();
        $controller-&gt;registerPlugin(new Bugapp_Plugin_Initialize('development'));
    }

    public function setUp()
    {
        $this-&gt;bootstrap = array($this, 'appBootstrap');
        parent::setUp();
    }

    // ...
}
</pre>
<p>
            Once we have that in place, we can write our tests. However, what
            about those tests that require a user is logged in? The easy
            solution is to use our application logic to do so... and fudge a
            little by using the <code class="code">resetResponse()</code> method, which will
            allow us to dispatch another request.
        </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function loginUser($user, $password)
    {
        $request = $this-&gt;getRequest();
        $request-&gt;setMethod('POST')
                -&gt;setPost(array(
                    'username' =&gt; $user,
                    'password' =&gt; $password,
                ));
        $this-&gt;dispatch('/user/login');
        $this-&gt;assertRedirectTo('/user/view');
        $this-&gt;resetResponse();
        $request-&gt;setPost(array());
    }

    // ...
}
</pre>
<p>
            Now let's write tests:
        </p>
<pre class="programlisting">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function testCallWithoutActionShouldPullFromIndexAction()
    {
        $this-&gt;dispatch('/user');
        $this-&gt;assertController('user');
        $this-&gt;assertAction('index');
    }

    public function testLoginFormShouldContainLoginAndRegistrationForms()
    {
        $this-&gt;dispatch('/user');
        $this-&gt;assertQueryCount('form', 2);
    }

    public function testInvalidCredentialsShouldResultInRedisplayOfLoginForm()
    {
        $request = $this-&gt;getRequest();
        $request-&gt;setMethod('POST')
                -&gt;setPost(array(
                    'username' =&gt; 'bogus',
                    'password' =&gt; 'reallyReallyBogus',
                ));
        $this-&gt;dispatch('/user/login');
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery('form');
    }

    public function testValidLoginShouldRedirectToProfilePage()
    {
        $this-&gt;loginUser('foobar', 'foobar');
    }

    public function testAuthenticatedUserShouldHaveCustomizedProfilePage()
    {
        $this-&gt;loginUser('foobar', 'foobar');
        $this-&gt;request-&gt;setMethod('GET');
        $this-&gt;dispatch('/user/view');
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQueryContentContains('h2', 'foobar');
    }

    public function testAuthenticatedUsersShouldBeRedirectedToProfilePageWhenVisitingLoginPage()
    {
        $this-&gt;loginUser('foobar', 'foobar');
        $this-&gt;request-&gt;setMethod('GET');
        $this-&gt;dispatch('/user');
        $this-&gt;assertRedirectTo('/user/view');
    }

    public function testUserShouldRedirectToLoginPageOnLogout()
    {
        $this-&gt;loginUser('foobar', 'foobar');
        $this-&gt;request-&gt;setMethod('GET');
        $this-&gt;dispatch('/user/logout');
        $this-&gt;assertRedirectTo('/user');
    }

    public function testRegistrationShouldFailWithInvalidData()
    {
        $data = array(
            'username' =&gt; 'This will not work',
            'email'    =&gt; 'this is an invalid email',
            'password' =&gt; 'Th1s!s!nv@l1d',
            'passwordVerification' =&gt; 'wrong!',
        );
        $request = $this-&gt;getRequest();
        $request-&gt;setMethod('POST')
                -&gt;setPost($data);
        $this-&gt;dispatch('/user/register');
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery('form .errors');
    }
}
</pre>
<p>
            Notice that these are terse, and, for the most part, don't look for
            actual content. Instead, they look for artifacts within the
            response -- response codes and headers, and DOM nodes. This allows
            you to verify that the structure is as expected -- preventing your
            tests from choking every time new content is added to the site.
        </p>
<p>
            Also notice that we use the structure of the document in our tests.
            For instance, in the final test, we look for a form that has a node
            with the class of "errors"; this allows us to test merely for the
            presence of form validation errors, and not worry about what
            specific errors might have been thrown.
        </p>
<p>
            This application <span class="emphasis"><em>may</em></span> utilize a database. If
            so, you will probably need some scaffolding to ensure that the
            database is in a pristine, testable configuration at the beginning
            of each test. PHPUnit already provides functionality for doing so;
            <a href="http://www.phpunit.de/pocket_guide/3.3/en/database.html" target="_top">read
                about it in the PHPUnit documentation</a>. We recommend
            using a separate database for testing versus production, and in
            particular recommend using either a SQLite file or in-memory
            database, as both options perform very well, do not require a
            separate server, and can utilize most SQL syntax.
        </p>
</div>
</div>
<br class="example-break">
</div>
</div>
<div class="navfooter"><table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="zend.test.html">Prev</a> </td>
<td width="20%" align="center"><a accesskey="u" href="zend.test.html">Up</a></td>
<td width="40%" align="right"> <a accesskey="n" href="zend.text.html">Next</a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 41. Zend_Test </td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
<td width="40%" align="right" valign="top"> Chapter 42. Zend_Text</td>
</tr>
</table></div>
<div class="revinfo"></div>
</body>
</html>
